package com.hzcx.app.simplechat.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.login.event.WxLoginSuccessEvent;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setIntent(intent);
//        api.handleIntent(intent, this);
//    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_wxentry);
        api = WXAPIFactory.createWXAPI(this, Common.WX_APP_ID, false);
        api.handleIntent(getIntent(), this);
        LogUtils.d("微信回调页启动");
    }

    @Override
    public void onReq(BaseReq baseReq) {
        LogUtils.d("baseReq");
    }

    @Override
    public void onResp(BaseResp baseResp) {
        String code="";
        try {
            SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
            code=newResp.code;
        }catch (Exception e){
            e.printStackTrace();
            code="";
        }

        LogUtils.d("收到微信回调："+code);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                EventBus.getDefault().post(new WxLoginSuccessEvent(true, "登录成功", code));
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                EventBus.getDefault().post(new WxLoginSuccessEvent(false, "取消登录", code));
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                EventBus.getDefault().post(new WxLoginSuccessEvent(false, baseResp.errStr, code));
                break;
            default:
                EventBus.getDefault().post(new WxLoginSuccessEvent(false, "未知错误", code));
                break;
        }
        finish();
    }
}
